<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use App\Http\Extend\Token;
class WechatController extends Controller
{
    public function doLogin(Request $request){
        try{
            $request->validate([
                'code'=>'required'
            ]);
        }catch (\Exception $e){
            exit(json_encode([
                'code'=>-1,
                'data'=>null,
                'msg'=>'code没传'
            ],JSON_UNESCAPED_UNICODE));
        }
        $code=$request->get('code');
        $appid='wxd38b61fce5b82c21';
        $opse='4f8baac18d272930f7ef4e4e4280b860';
        $wxLoginUrl= "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$opse}&js_code={$code}&grant_type=authorization_code";
        $result=file_get_contents($wxLoginUrl);
        $result=json_decode($result,true);

        if (isset($result['errcode']) && $result['errcode']!=0){
            exit(json_encode([
                'code'=>-1,
                'data'=>null,
                'msg'=>'微信服务异常'
            ],JSON_UNESCAPED_UNICODE));
        }

        $user=User::where('openid',$result['openid'])
            ->first();
        if (empty($user)){
            $user=User::create($result);
        }
        $token=(new Token())->genToken($user);

        return[
            'code'=>0,
            'data'=>$token,
            'msg'=>'登陆成功'
        ];
    }




    public function update(Request $request)
    {
        $token = $request->header('token');
        $userData=(new Token())->deToken($token);
        print_r($userData);die();
        $params=$request->all();
       User::where('id',$userData->data->avatar_id)
        ->first($params);
        return[
            'code'=>0,
            'data'=>null,
            'msg'=>'更新成功'
        ];

    }

}
